package com.jiangjupeng46.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.io.InputStream;

/**
 * MyBatis工具类（简化版，用于编译测试）
 */
public class MyBatisUtils {

    private static Object sqlSessionFactory;
    private static final String CONFIG_RESOURCE = "mybatis-config.xml";

    // 静态代码块初始化，使用反射避免编译错误
    static {
        try {
            // 尝试加载MyBatis相关类
            Class<?> resourcesClass = Class.forName("org.apache.ibatis.io.Resources");
            Class<?> sqlSessionFactoryClass = Class.forName("org.apache.ibatis.session.SqlSessionFactory");
            Class<?> sqlSessionFactoryBuilderClass = Class.forName("org.apache.ibatis.session.SqlSessionFactoryBuilder");
            
            // 使用反射调用方法
            Method getResourceAsStreamMethod = resourcesClass.getMethod("getResourceAsStream", String.class);
            InputStream inputStream = (InputStream) getResourceAsStreamMethod.invoke(null, CONFIG_RESOURCE);
            
            Constructor<?> builderConstructor = sqlSessionFactoryBuilderClass.getConstructor();
            Object builder = builderConstructor.newInstance();
            
            Method buildMethod = builder.getClass().getMethod("build", InputStream.class);
            sqlSessionFactory = buildMethod.invoke(builder, inputStream);
            
            inputStream.close();
        } catch (Exception e) {
            // 如果MyBatis类不可用，不抛出异常，只记录
            System.out.println("警告：MyBatis库可能没有添加到classpath中。运行测试时需要确保lib目录包含必要的JAR文件。");
            sqlSessionFactory = null;
        }
    }

    /**
     * 获取SqlSession对象
     * @return SqlSession对象或null
     */
    @SuppressWarnings("unchecked")
    public static <T> T getSqlSession() {
        try {
            if (sqlSessionFactory != null) {
                Method openSessionMethod = sqlSessionFactory.getClass().getMethod("openSession", boolean.class);
                return (T) openSessionMethod.invoke(sqlSessionFactory, true); // 自动提交
            } else {
                // 如果没有MyBatis，返回null
                System.out.println("错误：无法获取SqlSession，sqlSessionFactory为null");
                return null;
            }
        } catch (Exception e) {
            System.out.println("获取SqlSession时出错：" + e.getMessage());
            return null;
        }
    }

    /**
     * 关闭SqlSession
     * @param sqlSession SqlSession对象
     */
    public static void closeSqlSession(Object sqlSession) {
        try {
            if (sqlSession != null) {
                Method closeMethod = sqlSession.getClass().getMethod("close");
                closeMethod.invoke(sqlSession);
            }
        } catch (Exception e) {
            System.out.println("关闭SqlSession时出错：" + e.getMessage());
        }
    }

    /**
     * 检查是否成功初始化
     * @return 是否初始化成功
     */
    public static boolean isInitialized() {
        return sqlSessionFactory != null;
    }
}